<template>
 <div class="borrower">
      
      <el-card class="box-card" shadow="never" style="border:0px;">
                <el-button style="float:right;margin-right:18%;" type="primary" size="mini" v-if="defaultChangeValue!='detail'" @click="createProjectInfoDraft(2)" >保存草稿</el-button>
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="right" label-width="110px" style="width: 600px; margin-left:50px;">
        <el-form-item label="申请金额" prop="applyAmount">
          <el-input type="number" min="1" v-model="dataForm.applyAmount">
             <template slot="append">万</template>
          </el-input>
        </el-form-item>
         <el-form-item label="抵押类型" prop="pledgeType">
           <DicSelect dictType = "抵押类型" :dictValue="dataForm.pledgeType" v-on:dictValue="dataForm.pledgeType=$event"/>
        </el-form-item>
         <el-form-item label="申请期限" prop="applyTerm">
           <DicSelect dictType = "申请期限" :dictValue="dataForm.applyTerm" :disabledFlag="applyTermInput" v-on:dictValue="dataForm.applyTerm=$event"/>
        </el-form-item>
        <el-form-item label="还款方式" prop="repayMethod">
          <!-- <DicSelect dictType = "还款方式"  :dictValue="dataForm.repayMethod" v-on:dictValue="dataForm.repayMethod=$event"/> -->
           <el-select v-model="dataForm.repayMethod" @change="handleChangeRepayMethod" clearable placeholder="请选择" style="min-width:100%;">
            <el-option
              v-for="item in dictList"
              :key="item.dictValue"
              :label="item.dictName"
              :value="item.dictValue"/>
            </el-select>
        </el-form-item>
        <el-form-item label="开放城市" prop="openCity">
           <el-select 
            style="min-width:100%;"
            filterable
            v-model="dataForm.openCity" 
            placeholder="请选择开放城市" 
            clearable
           >
            <el-option v-for="(item) in chooseList" value-key="areaCode" :key="item.areaCode" :value="item.areaCode" :label="item.areaName"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="资方" prop="capitalSource">
          <DicSelect dictType = "资方" :dictValue="dataForm.capitalSource" v-on:dictValue="dataForm.capitalSource=$event"/>
        </el-form-item> -->
        <el-form-item label="渠道名称" prop="channelId">
           <el-select v-model="dataForm.channelId" clearable placeholder="请选择" style="min-width:100%;">
            <el-option
              v-for="item in channelList"
              :key="item.id"
              :label="item.channelName"
              :value="item.id"/>
            </el-select>
        </el-form-item>
          <el-form-item label="借款次数" prop="loanNumber">
          <el-input type="number" v-model="dataForm.loanNumber">
             <template slot="append">次</template>
          </el-input>
        </el-form-item>
         <el-form-item label="客户经理" prop="creatorId">
           <el-input v-model="dataForm.createName" disabled v-if="!isCustomerManager" placeholder="默认本人"/>
          <el-select 
            style="min-width:100%;"
            filterable
            v-model="dataForm.creatorId" 
            placeholder="请选择客户经理" 
            clearable
            v-else
            @change="change"
           >
            <el-option v-for="(item) in permissionList" value-key="userId" :key="item.userId" :value="item.userId" :label="item.displayName"></el-option>
          </el-select>
        </el-form-item>
         <el-form-item label="预约下户时间" prop="appointNextTime">
                <el-date-picker
                  style="width:100%"
                  v-model="dataForm.appointNextTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期">
                </el-date-picker>
        </el-form-item>
     
       
        
         <el-form-item>
        <el-button  type="warning" v-if=" defaultChangeValue === 'detail'" @click="createData" style="width:150px;height:40px;">保存</el-button>
        <div v-else>
           <el-button  type="primary" @click="createProjectInfoDraft(1)" style="width:150px;height:40px;">上一步</el-button>
           <el-button  type="warning" @click="createData(2)" style="width:150px;height:40px;">下一步</el-button>
        </div>
      </el-form-item>
      </el-form>
      </el-card>

  </div>
</template>



<script>
import { createProject,createProjectInfoDraft,updateProject,findProjectBytId,findByBorrowerId,findCityList,permissionList} from '@/api/project'
import { chooseChannel } from '@/api/channel'
import { listDict } from '@/api/dict'
import DicSelect from '@/components/select'
import { mapGetters } from 'vuex'
export default {
  name: 'projectInfo',
  components: { DicSelect },
  // 接受父组件的值
  props: {
     changeValue: undefined,
     projectId: undefined,
     operation: undefined
    }, 
  data() {
    return {
      isCustomerManager:false,
      defaultChangeValue: this.changeValue,
      appointNextTime:undefined,
      updateParam: undefined,
      list: undefined,
      total: 0,
      listLoading: true,
      options:[],
      dictList: [],
      channelList: [],
      chooseList: [],
      permissionList:[],
      value:undefined,
      borrowerId: undefined,
      stepType: undefined,
      applyTermInput: false,
      dataForm: {
        applyAmount: undefined,
        pledgeType: undefined,
        applyTerm: undefined,
        capitalSource: undefined,
        repayMethod: undefined,
        loanNumber: undefined,
        creatorId:undefined,
        createName: undefined,
        channelId: undefined,
        appointNextTime: undefined,
        borrowerId: undefined,
        openCity: undefined
      },
      data: [{
      }],
      rules: {
        applyAmount: [
          { required: true, message: '请输入申请金额', trigger: 'blur' },
        

      { 
        validator (rule, value, callback) {
          if( value.length > 5 ) {
             callback(new Error('金额过大，单位是万，请输入正确的金额'))
          }
          if (/(^[1-9]\d*$)/.test(value)) {
           callback()
          } else {
           callback(new Error('请输入正确的金额'))
          }
        },
        trigger: 'blur'
      }],
        pledgeType: [
          { required: true, message: '请选择抵押类型', trigger: 'change' }
        ],
        applyTerm: [
          { required: true, message: '请选择申请期限', trigger: 'change' }
        ],
        repayMethod: [
          { required: true, message: '请选择还款方式', trigger: 'change' }
        ],
        capitalSource: [
          { required: true, message: '请选择资方', trigger: 'change' }
        ],
        openCity: [
          {required:true, message:'请选择开放城市', trigger:'change'}
        ],
        channelId: [
          { required: true, message: '请输入渠道名称', trigger: 'blur' }
        ],
        loanNumber: [
          { required: true, message: '请输入借款次数', trigger: 'blur' }
        ],
        appointNextTime: [
          { required: true, message: '请选择下户时间', trigger: 'blur' }
        ]
      },
      downloadLoading: false
    }
  },
  watch: {
    "changeValue":function(val){
      this.defaultChangeValue = val
    }
  },
  computed: {
    ...mapGetters(['roles']),
  },
  created() {
    var form = localStorage.getItem("project")
    this.borrowerId = localStorage.getItem("borrowerId")
    if(form!= undefined){
      this.dataForm = JSON.parse(form)
    } 
    if(this.projectId != undefined) {
      this.findByProjectId()
      this.defaultChangeValue = "detail"
    }
    if(this.borrowerId != undefined) {
      this.findByBorrowerId()
    }
    this.getDictList();
    this.getChannelList();
    this.getChoose();
    this.getPermissionList();
    if( this.roles.indexOf("admin")!=-1 || this.roles.indexOf("销售助理岗")!=-1){
        this.isCustomerManager = true
    }
  },
  
  methods: {
    handleChangeRepayMethod(val){
        console.log(val)
        if( val === 1 ) {
          //如果选择先息后本 则申请期限只能为12
          this.dataForm.applyTerm = 4
          this.applyTermInput = true
        }else{
          this.applyTermInput = false
        }
    },
       findByProjectId() {
      this.listLoading = true
      findProjectBytId({projectId:this.projectId})
        .then(response => {
          if(response.data != undefined ) {
            this.dataForm = response.data
          }
        })
        .catch(() => {
          this.resetForm()
        })
    },
    findByBorrowerId() {
      this.listLoading = true
      findByBorrowerId({borrowerId:this.borrowerId})
        .then(response => {
          if(response.data != undefined ) {
            this.dataForm = response.data
          }
        })
        .catch(() => {
          this.resetForm()
        })
    },
    getDictList() {
      listDict({dictTypeName:"还款方式"})
        .then(response => {
          console.log(response.data)
          this.dictList = response.data
        })
        .catch(() => {
          this.dictList = []
        })
    },
    getChannelList() {
      chooseChannel()
        .then(response => {
          this.channelList = response.data
        })
        .catch(() => {
          this.channelList = []
        })
    },
    
    getChoose() {
      findCityList()
        .then((res) => {
          this.chooseList = res.data
        })
        .catch(() => {
           this.chooseList = []
        })
    },
    getPermissionList() {
      permissionList()
        .then((res) => {
          let data = res.data;
          let permissionList = this.permissionList
          let list = data.map(item => {
            item.userId = item.userId.toString(); 
            return item
          }) 
          this.permissionList = [...permissionList,...list]
        })
        .catch(() => {
           this.permissionList = []
        })
    },
    resetForm() {
      this.dataForm = {
        applyAmount: undefined,
        pledgeType: undefined,
        applyTerm: undefined,
        capitalSource: undefined,
        repayMethod: undefined,
        loanNumber: undefined,
        creatorId:undefined,
        createName: undefined,
        channelId: undefined,
        appointNextTime: undefined,
        borrowerId: undefined,
        openCity: undefined,
      }
    },
    getRowClass({rowIndex}){
      if (rowIndex == 0) {
        return 'background:#FAFAFA'
      } else {
        return ''
      }
    },
    backStep(){
      if( this.defaultChangeValue != 'detail' ) {
        this.$emit("stepChanged",2)
      }
      
    },
    createData(val) {
      // console.log(this.dataForm)
      // if( this.changeValue != 'detail' ) {
      //   this.$emit("stepChanged",4)
      // }
      this.stepType = val
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          console.log(this.dataForm)
            if( this.operation === 'add'){
              this.dataForm.borrowerId = this.borrowerId
              this.createProject()
            }else{
              this.updateProject()
            }
        }
      })
    },
    createProject(){
        createProject(this.dataForm)
            .then(response => {
              localStorage.setItem("projectId",response.data.id)
              // localStorage.setItem("project",JSON.stringify(this.dataForm))
              localStorage.setItem("requestMethod",'add')
              localStorage.setItem("projectIdByDraw",response.data.id)
              localStorage.setItem("pledgeType",this.dataForm.pledgeType)
               if( this.defaultChangeValue != 'detail' ) {
                  this.$emit("stepChanged",this.stepType === 1 ? 2 : 4)
                }else{
                    this.$emit('getCapital')
                  }
              this.$notify.success({
                title: '成功',
                message: '保存成功'
              })
            })
            .catch(response => {
            })
    },
    createProjectInfoDraft(val){
      this.stepType = val
      this.dataForm.borrowerId = this.borrowerId
        if(this.dataForm.applyAmount!=undefined && this.dataForm.applyAmount.length > 5 ) {
          this.$message.error("金额过大，单位是万，请输入正确的金额")
          return false
        }
        createProjectInfoDraft(this.dataForm)
            .then(response => {
              this.$notify.success({
                title: '成功',
                message: '草稿保存成功'
              })
              if( val === 2) {
                this.$router.push("/project/index")
              }else{
                localStorage.setItem("projectIdByDraw",response.data.id)
                if( this.defaultChangeValue != 'detail' ) {
                  this.$emit("stepChanged",this.stepType === 1 ? 2 : 4)
                }else{
                    this.$emit('getCapital')
                  }
              }
            })
            .catch(response => {
            })
    },
    updateProject(){
        updateProject(this.dataForm)
            .then(response => {
              localStorage.setItem("projectId",this.dataForm.id)
              // localStorage.setItem("project",JSON.stringify(this.dataForm))
              localStorage.setItem("requestMethod",'edit-'+this.projectId)
              localStorage.setItem("pledgeType",this.dataForm.pledgeType)
               if( this.defaultChangeValue != 'detail' ) {
                  this.$emit("stepChanged",this.stepType === 1 ? 2 : 4)
                }else{
                    this.$emit('getCapital')
                  }
              this.$notify.success({
                title: '成功',
                message: '编辑成功'
              })
            })
            .catch(response => {
            })
    },
    change(value) {
      let list = this.permissionList;
      let createName;
      list.map(item => {
        if(item.userId == value) {
          createName = item.dictTypeName
        }
      })
      this.dataForm.createName = createName;
    }
  }
}
</script>
